package com.wish.blessingroad.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.wish.blessingroad.common.Constant;
import com.wish.blessingroad.common.RedisKey;
import com.wish.blessingroad.config.ServiceException;
import com.wish.blessingroad.dao.BlessingMapper;
import com.wish.blessingroad.entity.Blessing;
import com.wish.blessingroad.entity.User;
import com.wish.blessingroad.entity.returnBean.InviteUser;
import com.wish.blessingroad.service.IBlessingService;
import com.wish.blessingroad.service.IUserService;
import com.wish.blessingroad.util.JedisUtil;
import com.wish.blessingroad.util.Pager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Tuple;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 祝福表 服务实现类
 * </p>
 *
 * @author dhc
 * @since 2019-02-18
 */
@Service
public class BlessingServiceImpl extends ServiceImpl<BlessingMapper, Blessing>
        implements IBlessingService {
    private static final Logger LOG = LoggerFactory.getLogger(BlessingServiceImpl.class);
    @Resource
    private BlessingMapper blessingMapper;
    @Autowired
    private IUserService userServiceImpl;
    @Autowired
    private JedisUtil jedisUtil;

    /**
     * 添加
     *
     * @param blessing
     * @return
     */
    @Override
    public int saveBlessing(Blessing blessing) {
        //赋值
        if (blessing.getCreateDate() == null) {
            blessing.setEndDate(LocalDateTime.now().plusYears(1));//过期时间后N年
        }
        blessing.setStatus(Constant.StaticBlessing.STATUS_BLESSING_INTEND);
        try {
            blessingMapper.insert(blessing);
        } catch (Exception e) {
            LOG.error("保存祝福表失败 blessing={}", new Gson().toJson(blessing));
            throw new ServiceException(10001, "保存祝福表失败");
        }
        return blessing.getId();

    }


    /**
     * 修改时或追加福的值时
     *
     * @param blessing
     * @return
     */
    @Override
    public boolean updateById(Blessing blessing) {
        Blessing blessing2 = blessing.selectById();
        //赋值
        if (blessing.getCreateDate() == null) {
            blessing.setUpdateDate(LocalDateTime.now());
            if (blessing.getFuValue() > 0) {
                blessing.setFuValue(blessing.getFuValue() + blessing2.getFuValue());
                blessing.setEndDate(LocalDateTime.now().plusYears(1));//过期时间后60天
            }
        }
        blessing.setStatus(Constant.StaticBlessing.STATUS_BLESSING_INTEND);
        return blessingMapper.updateById(blessing) > 0;
    }

    /**
     * 分页查询
     *
     * @param blessing
     * @param pageNumber 第几页
     * @param pageSize   每页多少
     * @return
     */
    @Override
    public IPage<Blessing> selectPage(Blessing blessing, int pageNumber, int pageSize) {
        Page<Blessing> page = new Page<Blessing>(pageNumber, pageSize);
        QueryWrapper<Blessing> queryWrapper = new QueryWrapper<>();
        if (blessing.getUserId() != null && blessing.getUserId() > 0) {
            queryWrapper.lambda().eq(Blessing::getUserId, blessing.getUserId());
        }
        if (blessing.getStatus() != null && blessing.getStatus() > 0) {
            queryWrapper.lambda().eq(Blessing::getStatus, blessing.getStatus());
        }
        if (blessing.getType() != null && blessing.getType() > 0) {
            queryWrapper.lambda().eq(Blessing::getType, blessing.getType());
        }
        if (blessing.getCreateDateS() != null && blessing.getCreateDateE() != null) {
            queryWrapper.lambda().between(Blessing::getCreateDate, blessing.getCreateDateS(),
                    blessing.getCreateDateE());
        }
        if (blessing.getExcuteDateE() != null && blessing.getExcuteDateS() != null) {
            queryWrapper.lambda().between(Blessing::getExcuteDate, blessing.getExcuteDateS(),
                    blessing.getExcuteDateE());
        }
        queryWrapper.orderByDesc("create_date");
        IPage<Blessing> page1 = blessingMapper.selectPage(page, queryWrapper);
        return page1;
    }

    @Override
    public List<InviteUser> rankingBlessing(int pageNum, int pageSize) {
        var pager = new Pager(pageSize, pageNum);
        int sNum = pager.getPageStart(pageNum, pageSize);
        List<InviteUser> list = new ArrayList<>();
        //查询redis
        Set<Tuple> tupleSet = jedisUtil.zrevrangeWithScores(RedisKey.RANKING_LIST_USER,
                sNum, sNum+pageSize);
        tupleSet.forEach(obj -> {
            var id = Integer.valueOf(obj.getElement());
            User user = userServiceImpl.getUserById(id+"");
            list.add(new InviteUser(id, user.getName(), (int) obj.getScore()));
        });
        return list;
    }

    @Override
    public void delBlessingEndTime(String time, int status) {
        blessingMapper.deleteEndDate(time, status);
    }
}
